package 多线程.复习.线程方法;

import 多线程.复习.线程常用属性.ThreadAttr;

import java.util.Random;
import java.util.concurrent.*;

public class 生产消费者 {

    public static void main(String[] args) {
        BlockingQueue blockingDeque = new LinkedBlockingQueue(2);
        Thread t1 = new Thread(() -> {
            while (true){
                try {
                    int val = (int) blockingDeque.take();
                    System.out.println("消费者消费：" + val);
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        },"消费者");
        Random random = new Random();
        Thread t2 =new Thread(() -> {
            while (true){
                try {
                    int val = random.nextInt(100);
                    System.out.println("生产者生产：" + val);
                    blockingDeque.put(val);//在次设置为墙，防止指令重排
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

            }
        },"生产者");
        t1.start();
        t2.start();
    }
}
